//
//  HMOuthViewController.swift
//  TJHWeiBo
//
//  Created by tianjunhui on 16/8/10.
//  Copyright © 2016年 itcast.cn. All rights reserved.
//

import UIKit

class HMOuthViewController: UIViewController {
    
    override func loadView() {
        
        
        view = webView
        //判断URL是否为nil
        guard let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(WBAppKey)&redirect_uri=\(WBRedirect_uri)") else{
            return
        }
        
        //获取code码 设置代理
        webView.delegate = self
        
        //实例化request
        let request = NSURLRequest(URL: url)
        //记载request
        webView.loadRequest(request)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        setUI()
    }
    //返回的监听方法
    @objc  private func cancelAction(){
        dismissViewControllerAnimated(false, completion: nil)
    }
    //登录的响应事件
    @objc private func longAction(){
        print("自动填充")
        let jsString = "document.getElementById('userId').value='\(WBName)',document.getElementById('passwd').value='\(WBPassWd)'"
        //
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
        
    }
    //设置视图
    private func setUI(){
        view.backgroundColor = UIColor .whiteColor()
        setNav()
    }
    
    //设置导航
    private func setNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem (title: "返回", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HMOuthViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem (title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(HMOuthViewController.longAction))
        navigationItem.title = "微博登录"
        
    }
    
    //懒加载控件
    private lazy var webView: UIWebView = UIWebView()
    
    
}

//代理方法
extension HMOuthViewController: UIWebViewDelegate{
    
    //监听 webView 将要加载的request 如果不实现就返回true 如果返回false 停止加载
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let urlString = request.URL?.absoluteString where urlString.hasPrefix(WBRedirect_uri){
            //判断是否为空
            if let query = request.URL?.query {
                //获取code
                let code = query.substringFromIndex("code=".endIndex)
                print(code)
               
                
                HMUserAccountViewModel.sharedTools.getUserAccount(code, finish: { (isSuccess) in
                    if !isSuccess {
                        print("请求失败")
                        return
                    }
                    print("请求成功")
//                    let result = HMUserAccountViewModel.sharedTools.userAccount
                    self.dismissViewControllerAnimated(false, completion: {
                         NSNotificationCenter.defaultCenter().postNotificationName(WBSWITCHROOTVCNOTIFICATION, object: "oauth")
                    })
                   
                    
                    
//                    print(result)
                })
                
                return false
            }
        }
        
        
        
        return true
        
    }
    
}




